package com.maiji.cloud.utils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alipay.api.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.maiji.cloud.request.shopingmall.AlipayRefundReqData;
import com.maiji.cloud.request.shopingmall.AlipayRefundReqData.RefundReqInner;

import org.apache.commons.lang.StringUtils;

public class AlipayUtil {

	public static final String APP_ID = "2019072665914982";
	// 支付宝支付私钥
	public static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVraOKW6d4sSnNrH0JZZHSaclv5SyXzJoKW8QGw37HBbIBAqhC8vx7nCJ47Lt2sHw9mzQK0F+uo6ldGui1asixIaSR0vC2Kkt5k5dLkExoBjjbk2Gv7BXkEXkHXXSF/9tJlm2fs+9Q09VFXxBw+Bf+CnuqufGKLyoKbNqbTcwg5VzgK6HOHY0P3/Hab4LLzhiDl+wdeKsKP2VXAEh+H3J6qfPjt7SFfG7sPtxRzm+Kymn94BmSMu/VodLn54vtE7eHhgULPWu3hrDJoGBN6Fbt3uZvi0U8q4iNFDD5YuENMOztKzgUiQuh4N3Sbd6BOKBoh0akPDV5jdv7NU9bslrjAgMBAAECggEARfgBty/ZPcYzsH2thbMBU8c37yLGkb+HUshK/o5suUSkTWyck49bD72RL84aZAVkTrg6v8NgtxaymV924Tel0YfUkoZ1F/L1jUO9OgmebhJaiep/g+ls4kx4s0Swr+N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
	public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm1zz5T4042v+LzDVLfiHw2GjLs6exfyiVIYPofDyGHGtYmUAgXz7Pzj1U5WWW8eODqt+4FrctnWjbjhDJ97kC4V67ja4uswP5U+y5hin83PorUgXQc0khdUoKU720hnEeMMl3Q1Q5DiSWTYsK+MqSwkR7jXP1MB7KIWlq+BggXg9mlTMYlLXGiGZV3QIHJv13PylCrgcSnsiJWwlQkeChf3qH9NWwhZDPKJqQr8V25f1oUi6CR+T7maGQtRti2UdzYrgxTth2wYsIoSiIjXqqvjxaBch+u1vHSkRipnNnPCfhRkEs8xvWFkZQjWmkia6ti+rdrVhpoS4GqjDO52z/wIDAQAB";
	//支付支付成功回调url
    public static final String NOTIFY_URL = "https://api.imaiji.cn/capitalInteface/alipayCallBack";
	
	public static String createSign(Map parameters) throws Exception {

        List<String> keys = new ArrayList<String>(parameters.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        Object value = parameters.get(key);
//        value = URLEncoder.encode(value, "UTF-8");
        if(StringUtils.isNotBlank(parameters.get(key)+"") && value != null) {
        	if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }	
        }
        }
        return prestr;
    }
	
	public static String createSignValues(Map parameters) throws Exception {

        List<String> keys = new ArrayList<String>(parameters.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        Object value = parameters.get(key);
        if(StringUtils.isNotBlank(parameters.get(key)+"") && value != null) {
        	value = URLEncoder.encode(value+"", "UTF-8");
        	if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }	
        }
        }
        return prestr;
    }


    public static void main (String[] args) throws Exception {
        
//    	AlipayClient alipayClient = new DefaultAlipayClient
//				("https://openapi.alipay.com/gateway.do",AlipayUtil.APP_ID,AlipayUtil.PRIVATE_KEY,"json","utf-8",AlipayUtil
//				.PUBLIC_KEY,"RSA2");
//        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("out_biz_no", "");
//        
//        request.setBizContent("{" +
//        "\"out_biz_no\":\"950811\"," +
//        "\"payee_type\":\"ALIPAY_LOGONID\"," +
//        "\"payee_account\":\"18365728973\"," +
//        "\"payee_real_name\":\"张丽锐\"," +
//        "\"amount\":\"0.1\"," +
//        "\"remark\":\"转账备注\"" +
//        "  }");
//        AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
    	
    	AlipayFundTransToaccountTransferResponse response = AlipayUtil.alipayWithdraw(UUID_MD5.getUUID(), "张丽锐", "18365728973",0.1 );
        System.out.println(JSON.toJSONString(response));
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }

    public static AlipayFundTransToaccountTransferResponse alipayWithdraw(String ioUuid,String realName,String account,Double amount) throws AlipayApiException{
    	 Map<String, Object> map = new HashMap<String, Object>();
         map.put("out_biz_no", ioUuid);
         map.put("payee_type", "ALIPAY_LOGONID");
         map.put("payee_account", account);
         map.put("payee_real_name", realName);
         map.put("amount", amount);
         map.put("remark", "提现");
         
         AlipayClient alipayClient = new DefaultAlipayClient ("https://openapi.alipay.com/gateway.do", AlipayUtil.APP_ID,
                 AlipayUtil.PRIVATE_KEY, "json", "utf-8",  AlipayUtil.PUBLIC_KEY,"RSA2");
         AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
         
         request.setBizContent(JSON.toJSONString(map));
         AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
    	return response;
    	
    }
    
    public static AlipayTradeRefundResponse alipayRefund(String orderNo,String payId, Double refundMoney) throws Exception {
    	String nowTime = TimeUtil.date2String(new Date(), null);
		AlipayRefundReqData aliPayResData = new AlipayRefundReqData();
		aliPayResData.setApp_id(AlipayUtil.APP_ID);
		aliPayResData.setCharset("utf-8");
		aliPayResData.setMethod("alipay.trade.refund");
		aliPayResData.setSign_type("RSA2");
		aliPayResData.setTimestamp(nowTime);
		aliPayResData.setVersion("1.0");
		RefundReqInner aliPayResInner = aliPayResData.dataInstance();
		aliPayResInner.setOut_trade_no(orderNo);
		aliPayResInner.setRefund_amount(refundMoney);
		aliPayResInner.setTrade_no(payId);
		aliPayResInner.setOut_request_no(orderNo);
		Map paramMap = WXUtil.objectToMap(aliPayResData);
		paramMap.remove("biz_content");
		paramMap.put("biz_content", JSON.toJSON(aliPayResInner));

		String signString = AlipayUtil.createSign(paramMap);
		String sign = AlipaySignature.rsaSign(signString, AlipayUtil.PRIVATE_KEY, "utf-8", "RSA2");
		aliPayResData.setSign(sign);
		paramMap.put("sign", sign);
		AlipayClient alipayClient = new DefaultAlipayClient
				("https://openapi.alipay.com/gateway.do",AlipayUtil.APP_ID,AlipayUtil.PRIVATE_KEY,"json","utf-8",AlipayUtil
				.PUBLIC_KEY,"RSA2");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		request.setBizContent( JSON.toJSONString(aliPayResInner));
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		if (!"Y".equals(response.getFundChange())) {
			throw new Exception("调用退款接口退款未成功");
		}

		return response;
    }



}
